<template>
  <div class="chat-app" :class="chatAppClasses">
    <!-- Left Sidebar -->
    <BigLeft
      v-if="!ui.shouldCollapseSidebar"
      :navigation="navigationItems"
      :active-item="ui.activeTab"
      @navigate="handleNavigate"
      class="chat-app__sidebar"
    />
    
    <!-- Mobile Sidebar Overlay -->
    <div
      v-if="ui.isMobile && !ui.sidebarCollapsed"
      class="chat-app__overlay"
      @click="ui.setSidebarCollapsed(true)"
    />
    
    <!-- Right Content Area -->
    <RightContent
      :title-bar-props="titleBarProps"
      :right-bottom-props="rightBottomProps"
      class="chat-app__content"
    />
    
    <!-- Loading Overlay -->
    <div v-if="isLoading" class="chat-app__loading">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>
    </div>
    
    <!-- Error Toast -->
    <div
      v-for="notification in ui.notifications"
      :key="notification.id"
      :class="[
        'chat-app__notification',
        `chat-app__notification--${notification.type}`
      ]"
    >
      <div class="notification-content">
        <h4>{{ notification.title }}</h4>
        <p>{{ notification.message }}</p>
      </div>
      <button
        @click="ui.removeNotification(notification.id)"
        class="notification-close"
      >
        ×
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue'
import { useStores } from '@/composables'
import type { NavigationItem, TitleBarProps, RightBottomProps } from '@/types'
import BigLeft from './BigLeft.vue'
import RightContent from './RightContent.vue'

// Props
interface Props {
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Stores
const { userStore: user, chatStore: chat, uiStore: ui, clientStore: client } = useStores()

// Computed properties
const chatAppClasses = computed(() => ({
  'chat-app--mobile': ui.isMobile,
  'chat-app--tablet': ui.isTablet,
  'chat-app--desktop': ui.isDesktop,
  'chat-app--sidebar-collapsed': ui.shouldCollapseSidebar,
  'chat-app--client-info-hidden': ui.shouldHideClientInfo,
  'chat-app--dark': ui.theme === 'dark'
}))

const isLoading = computed(() => {
  return props.loading || user.loading || chat.loading || client.loading
})

const navigationItems = computed<NavigationItem[]>(() => [
  {
    id: 'chats',
    label: '聊天',
    icon: 'chat',
    path: '/chats'
  },
  {
    id: 'contacts',
    label: '联系人',
    icon: 'contacts',
    path: '/contacts'
  },
  {
    id: 'settings',
    label: '设置',
    icon: 'settings',
    path: '/settings'
  }
])

const titleBarProps = computed<TitleBarProps>(() => ({
  chatTitle: chat.activeChatData?.title || '选择聊天',
  clientName: client.clientName || '未选择客户',
  onlineStatus: chat.activeChatData?.participants.some(p => p.status === 'online') || false,
  actions: [
    {
      id: 'toggle-client-info',
      label: ui.clientInfoVisible ? '隐藏客户信息' : '显示客户信息',
      icon: 'info',
      onClick: () => ui.toggleClientInfo()
    },
    {
      id: 'search',
      label: '搜索',
      icon: 'search',
      onClick: () => ui.openModal('search')
    },
    {
      id: 'more',
      label: '更多',
      icon: 'more',
      onClick: () => ui.openModal('chatActions')
    }
  ]
}))

const rightBottomProps = computed<RightBottomProps>(() => ({
  tabsProps: {
    chatList: chat.sortedChatList.map(chatItem => ({
      id: chatItem.id,
      name: chatItem.participants.find(p => p.id !== user.currentUser?.id)?.name || '未知用户',
      avatar: chatItem.participants.find(p => p.id !== user.currentUser?.id)?.avatar || '/default-avatar.png',
      lastMessage: chatItem.lastMessage?.content || '暂无消息',
      timestamp: chatItem.lastMessage?.timestamp || chatItem.updatedAt,
      unreadCount: chatItem.unreadCount,
      status: chatItem.participants.find(p => p.id !== user.currentUser?.id)?.status || 'offline'
    })),
    activeChat: chat.activeChat || '',
    onChatSelect: (chatId: string) => chat.setActiveChat(chatId)
  },
  chatMidProps: {
    messageHistoryProps: {
      messages: chat.activeChatMessages,
      loading: chat.loading,
      onLoadMore: () => {
        if (chat.activeChat) {
          chat.loadChatMessages(chat.activeChat)
        }
      }
    },
    messageInputProps: {
      onSendMessage: (content: string) => chat.sendMessage(content),
      placeholder: '输入消息...',
      disabled: !chat.activeChat || chat.loading
    }
  },
  clientInfoProps: {
    client: client.currentClient,
    tags: client.availableTags,
    onUpdateClient: (data) => client.updateClient(data)
  }
}))

// Methods
const handleNavigate = (itemId: string) => {
  ui.setActiveTab(itemId)
  
  // Handle navigation logic
  switch (itemId) {
    case 'chats':
      // Load chats if not already loaded
      if (chat.chatList.length === 0) {
        chat.loadChats()
      }
      break
    case 'contacts':
      // Load contacts
      break
    case 'settings':
      ui.openModal('settings')
      break
  }
}

const handleKeyboardShortcuts = (event: KeyboardEvent) => {
  // Global keyboard shortcuts
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 'k':
        event.preventDefault()
        ui.openModal('search')
        break
      case 'n':
        event.preventDefault()
        ui.openModal('createChat')
        break
      case ',':
        event.preventDefault()
        ui.openModal('settings')
        break
    }
  }
  
  // Escape key
  if (event.key === 'Escape') {
    ui.closeAllModals()
  }
}

const handleWindowResize = () => {
  ui.updateWindowSize(window.innerWidth, window.innerHeight)
}

// Lifecycle
onMounted(() => {
  // Initialize stores
  user.initialize()
  chat.initialize()
  ui.initialize()
  client.initialize()
  
  // Enable keyboard shortcuts
  ui.enableKeyboardShortcuts()
  
  // Add event listeners
  document.addEventListener('keydown', handleKeyboardShortcuts)
  window.addEventListener('resize', handleWindowResize)
  
  // Start auto-save
  user.startAutoSave()
  
  // Show welcome notification for new users
  if (user.isAuthenticated && !localStorage.getItem('welcome_shown')) {
    ui.addNotification({
      type: 'info',
      title: '欢迎使用聊天系统',
      message: '您可以使用快捷键 Ctrl+K 搜索，Ctrl+N 创建新聊天',
      duration: 8000
    })
    localStorage.setItem('welcome_shown', 'true')
  }
})

onUnmounted(() => {
  // Cleanup
  ui.cleanup()
  ui.disableKeyboardShortcuts()
  
  // Remove event listeners
  document.removeEventListener('keydown', handleKeyboardShortcuts)
  window.removeEventListener('resize', handleWindowResize)
})
</script>

<style scoped>
.chat-app {
  display: grid;
  grid-template-columns: var(--sidebar-width) 1fr;
  grid-template-rows: 1fr;
  height: 100vh;
  width: 100vw;
  background-color: var(--color-background);
  color: var(--color-text-primary);
  font-family: var(--font-family-base);
  overflow: hidden;
}

/* Responsive layouts */
.chat-app--mobile {
  grid-template-columns: 1fr;
}

.chat-app--sidebar-collapsed {
  grid-template-columns: 1fr;
}

.chat-app--tablet {
  grid-template-columns: var(--sidebar-width) 1fr;
}

.chat-app--desktop {
  grid-template-columns: var(--sidebar-width) 1fr;
}

/* Dark theme */
.chat-app--dark {
  background-color: #1a1a1a;
  color: #ffffff;
}

/* Layout components */
.chat-app__sidebar {
  grid-column: 1;
  grid-row: 1;
  z-index: var(--z-fixed);
}

.chat-app__content {
  grid-column: 2;
  grid-row: 1;
  min-width: 0; /* Prevent overflow */
}

.chat-app--mobile .chat-app__content,
.chat-app--sidebar-collapsed .chat-app__content {
  grid-column: 1;
}

/* Mobile overlay */
.chat-app__overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: calc(var(--z-fixed) - 1);
  backdrop-filter: blur(2px);
}

/* Loading overlay */
.chat-app__loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: var(--z-modal);
}

.chat-app--dark .chat-app__loading {
  background-color: rgba(26, 26, 26, 0.9);
}

.loading-spinner {
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid var(--color-border);
  border-top: 4px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto var(--spacing-md);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Notifications */
.chat-app__notification {
  position: fixed;
  top: var(--spacing-lg);
  right: var(--spacing-lg);
  min-width: 300px;
  max-width: 400px;
  padding: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-lg);
  z-index: var(--z-tooltip);
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-md);
  animation: slideInFromRight 0.3s ease-out;
}

.chat-app__notification--success {
  background-color: var(--color-success);
  color: white;
}

.chat-app__notification--error {
  background-color: var(--color-error);
  color: white;
}

.chat-app__notification--warning {
  background-color: var(--color-warning);
  color: white;
}

.chat-app__notification--info {
  background-color: var(--color-info);
  color: white;
}

.notification-content {
  flex: 1;
}

.notification-content h4 {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-semibold);
}

.notification-content p {
  margin: 0;
  font-size: var(--font-size-xs);
  opacity: 0.9;
}

.notification-close {
  background: none;
  border: none;
  color: inherit;
  font-size: var(--font-size-lg);
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--border-radius-sm);
  transition: background-color var(--transition-fast);
}

.notification-close:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .chat-app__notification {
    top: var(--spacing-sm);
    right: var(--spacing-sm);
    left: var(--spacing-sm);
    min-width: auto;
    max-width: none;
  }
}

/* Animations */
@keyframes slideInFromRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* Focus management */
.chat-app:focus-within {
  outline: none;
}

/* Print styles */
@media print {
  .chat-app__sidebar,
  .chat-app__loading,
  .chat-app__notification {
    display: none !important;
  }
  
  .chat-app {
    grid-template-columns: 1fr;
  }
}
</style>